//
//  WSSearchRequest.m
//  CharonTVProject
//
//  Created by karong on 2023/8/1.
//

#import "WSSearchRequest.h"

@implementation WSSearchRequest
+ (void)loadcharonTV_HotSearchSuccess:(charonTV_ArrayBlock)success failed:(Failure)failed {
    NSString * url = API_CHARONTV_SEARCH_HOT;
    NSDictionary * parameters = @{};
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        NSMutableArray * array = [WSVideo mj_objectArrayWithKeyValuesArray:responseDict[@"items"]];
        success(array);
    } failure:failed];
}

+ (void)loadcharonTV_SearchWithKeyWord:(NSString *)keyword page:(NSInteger)page success:(nonnull charonTV_ArrayBlock)success failed:(nonnull Failure)failed {
    NSString * url = API_CHARONTV_BOOK_SEARCH;
    NSDictionary * parameters = @{@"keyword":WSEmptyStr(keyword),
                                  @"page":@(page)
    };
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        NSMutableArray * array = [WSVideo mj_objectArrayWithKeyValuesArray:responseDict[@"items"]];
        success(array);
    } failure:failed];
}

#pragma mark - PagableRequestPotocol
- (void)refreshDataSuccess:(charonTV_ArrayBlock)success failed:(Failure)failed {
    if (self.loading) {
        return;
    }
    self.loading = YES;
    self.haveMore = YES;
    self.page = 1;
    [WSSearchRequest loadcharonTV_SearchWithKeyWord:self.keycharonTV_Word page:self.page success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}


- (void)loadMoreDataSuccess:(charonTV_ArrayBlock)success failed:(Failure)failed {
    if (self.loading && !self.haveMore) {
        return;
    }
    
    [WSSearchRequest loadcharonTV_SearchWithKeyWord:self.keycharonTV_Word page:self.page success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}

- (void)loadSuccess:(charonTV_ArrayBlock)success withArray:(NSArray *)array {
    self.haveMore = array.count == 10;
    self.page++;
    self.loading = NO;
    success(array);
}
@end
